package com.dandelion.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.dandelion.commons.utils.StringUtils;
import com.dandelion.manager.system.domain.Permit;
import com.dandelion.manager.system.domain.Resource;
import com.dandelion.manager.system.domain.Role;
import com.dandelion.manager.system.domain.RoleResource;
import com.dandelion.manager.system.domain.User;
import com.dandelion.manager.system.service.PermitService;
import com.dandelion.manager.system.service.RoleService;
import com.dandelion.manager.system.service.UserService;

public class ShiroAuthRealm extends AuthorizingRealm {
	
	private static final Logger logger = LogManager.getLogger(ShiroAuthRealm.class) ;
	
	@Autowired
	private UserService userService ;
	
	@Autowired
	private RoleService roleService ;
	
	@Autowired
	private PermitService permitService ;

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//System.out.println("验证当前Subject时获取到token为：" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));
		
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token; 
		String username = usernamePasswordToken.getUsername(); 				//账号
		//String password = new String(usernamePasswordToken.getPassword()); 	//密码
		
		User user = this.userService.findByUsername(username) ;
		
		if (user == null) {
			throw new UnknownAccountException(); 	//没找到帐号
		} else if (user.getLocked() == -1) { 		//账号被锁定
			throw new DisabledAccountException();
		}
		
		return new SimpleAuthenticationInfo(
				username, 
				user.getPassword(), 
				ByteSource.Util.bytes(user.getCredentialsSalt()), 
				getName());
	}
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		List<String> roles = new ArrayList<String>();   
		List<String> permissions = new ArrayList<String>();
		String username = (String) super.getAvailablePrincipal(principals) ; //账号
		
		User user = this.userService.findByUsername(username) ;
		
		if(null != user.getAuth() && user.getAuth().getRole_ids().length() > 0) {
			List<Role> list = this.roleService.selectRoleLinkRoleResourceIn(user.getAuth().getRole_ids());
			for (Role r : list) {
				roles.add(r.getIdentity()) ;
				
				List<RoleResource> roleResource = r.getRoleResource() ;
				List<Resource> resources = r.getResources() ;
				
				for(int i=0;i<resources.size();i++) {
					if(!roleResource.isEmpty()) {
						List<Permit> selectPermitByResource = this.permitService.selectPermitByResource(StringUtils.split(roleResource.get(i).getPermit_ids(), ",")) ;
						for (Permit permit : selectPermitByResource) {
							permissions.add(resources.get(i).getIdentity()+":"+permit.getIdentity());
						}
					}
				}
			}
		}
		
		logger.debug("账号：{}", username);
		logger.debug("角色：{}", roles);
		logger.debug("权限：{}", permissions);
		
		//为当前用户设置角色和权限  
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();  
		authorizationInfo.addRoles(roles);  
		authorizationInfo.addStringPermissions(permissions);  
		         
		return authorizationInfo;
	}


	@Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

    @Override
    public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
        super.clearCachedAuthenticationInfo(principals);
    }

    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }

    public void clearAllCachedAuthorizationInfo() {
        getAuthorizationCache().clear();
    }

    public void clearAllCachedAuthenticationInfo() {
        getAuthenticationCache().clear();
    }

    public void clearAllCache() {
        clearAllCachedAuthenticationInfo();
        clearAllCachedAuthorizationInfo();
    }
}
